﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class WebForm5 : System.Web.UI.Page
    {
        //更新数据库数据
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int id =Convert.ToInt32(Request["id"]);
                MySqlConnection cn = new MySqlConnection("server=localhost;uid = root;database=data;charset=utf8");
                //2）适配器帮我们查数据  参数：1）查什么 2）数据连接管道
                MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter("select* from student where id="+id, cn);
                //3)创建一个内存容器，创建一个空容器
                DataSet ds = new DataSet();
                //4)将数据从适配器中填入到容器中
                mySqlDataAdapter.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    textname.Text = ds.Tables[0].Rows[0]["name"].ToString();
                    textpwd.Text = ds.Tables[0].Rows[0]["pwd"].ToString();
                    texttel.Text = ds.Tables[0].Rows[0]["tel"].ToString();
                    //texttime.Text = ds.Tables[0].Rows[0]["time"].ToString();
                    textsex.SelectedValue = ds.Tables[0].Rows[0]["sex"].ToString();
                    texttype.SelectedValue = ds.Tables[0].Rows[0]["type"].ToString();

                }
                else
                {
                    Response.Write("<script>alert('没有学生信息');window.location.href='WebForm4.aspx'</script>");
                }

            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            int id=Convert.ToInt32(Request["id"]);
            string name = textname.Text.Trim();//trim去除空格
            int pwd = Convert.ToInt32(textpwd.Text.Trim());
            int sex = Convert.ToInt32(textsex.SelectedValue);
            string tel = texttel.Text.Trim();
            int type = Convert.ToInt32(texttype.SelectedValue);
            MySqlConnection connection = new MySqlConnection("server=localhost;uid = root;database=data;charset=utf8");
            string sql = string.Format("update student set name='{0}',pwd={1},sex='{2}',tel={3},type={4} where id={5}", name, pwd, sex, tel, type, id);
            MySqlCommand cmd = new MySqlCommand(sql, connection);

            //打开数据库
            connection.Open();
            int flag = cmd.ExecuteNonQuery();//执行并返回受影响行数
            connection.Close();
            if (flag == 1)
            {
                Response.Write("<script>alert('更新成功');window.location.href='WebForm4.aspx'</script>");
            }

        }
    }
}